package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.dto.PostDto;
import com.heima.mapper.PostMapper;
import com.heima.pojo.Post;
import com.heima.service.PostService;
import com.heima.vo.PageResult;
import com.heima.vo.PostVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class PostServiceImpl implements PostService {
    @Autowired
    private PostMapper postMapper;

    /**
     * 岗位列表
     * @param postDto
     * @return
     */
    @Override
    public PageResult list(PostDto postDto) {
        PageHelper.startPage(postDto.getPageNum(),postDto.getPageSize());
        Page<PostVo> page = postMapper.list(postDto);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getResult());
        return pageResult;
    }

    /**
     * 新增岗位
     */
    @Override
    public void add(PostDto postDto) {
        Post post = new Post();
        //生成三位数随机整数
        Integer random = new Random().nextInt(999)+100 ;
        //判断生成的随机数不等于已有的编号，等于时重新生成直到不等于
        //死循环
        while (true){
            if(postMapper.selectCountById(random) == 0){
                break;
            }else{
                random = new Random().nextInt(999)+100 ;
                log.info("生成的随机数为：{}",random);
            }
        }
        post.setPostId(random);
        post.setPostCode(postDto.getPostCode());
        post.setPostName(postDto.getPostName());
        post.setPostSort(postDto.getPostSort());
        post.setStatus(postDto.getStatus());
        post.setCreateTime(LocalDateTime.now());
        postMapper.add(post);
    }

    /**
     * 根据id查询岗位
     * @param postId
     * @return
     */
    @Override
    public PostVo getById(Integer postId) {
        PostVo post = postMapper.getById(postId);
        return post;
    }

    @Override
    public void deleteByIds(List<Integer> postIds) {
        postMapper.deleteByIds(postIds);
    }

    /**
     * 修改岗位
     * @param postDto
     */
    @Override
    public void updateCourse(PostDto postDto) {
        Post post = new Post();
        post.setPostId(postDto.getPostId());
        post.setPostCode(postDto.getPostCode());
        post.setPostName(postDto.getPostName());
        post.setPostSort(postDto.getPostSort());
        post.setStatus(postDto.getStatus());
        postMapper.updateCourse(post);
    }


}
